import { defineStore } from 'pinia'
import { ref, type Ref } from 'vue'
import { getLoginUserUsingGet } from '@/api/userController'

export const useUserStore = defineStore(
  'user',
  () => {
    const user: Ref<API.UserVO> = ref({})

    const token: Ref<string> = ref('')
    const tokenName: string = 'jiyan'

    async function getUserInfo() {
      const res: any = await getLoginUserUsingGet()
      if (res.code == 0) {
        user.value = res.data
      }
    }
    function setToken(token: string) {
      localStorage.setItem(tokenName, JSON.stringify(token))
    }

    function getToken() {
      const storedToken = localStorage.getItem(tokenName)
      return storedToken ? JSON.parse(storedToken) : null
    }

    function clearToken() {
      localStorage.removeItem(tokenName)
    }
    function logout() {
      clearToken()
      user.value = {}
    }
    return { user, token, getUserInfo, logout, setToken, getToken, clearToken }
  },
  {
    persist: true
  }
)
